package C7_5_CompositeReplaceImplicitTree.after;


import C7_5_CompositeReplaceImplicitTree.TagNode;

/**
 * @author xufy
 * @version 1.0
 **/
public class OrdersWriter {

    private Orders orders;

    public OrdersWriter(Orders orders) {
        this.orders = orders;
    }

    public String getContents() {
        StringBuffer xml = new StringBuffer();
        writeOrderTo(xml);
        return xml.toString();
    }

    private void writeOrderTo(StringBuffer xml) {
//        xml.append("<orders>");
//        for (int i = 0; i < orders.getOrderCount(); i++) {
//            Order order = orders.getOrder(i);
//            xml.append("<order>");
//            xml.append(" id='");
//            xml.append(order.getOrderId());
//            xml.append("'>");
//            writeProductsTo(xml, order);
//            xml.append("</order>");
//        }
//        xml.append("</orders>");
        TagNode ordersTag=new TagNode("orders");
        for (int i = 0; i < orders.getOrderCount(); i++) {
            Order order=orders.getOrder(i);
            TagNode orderTag=new TagNode("order");
            orderTag.addAttribute("id",order.getOrderId());
            writeProductsTo(orderTag,order);
            ordersTag.add(ordersTag);
        }
        xml.append(ordersTag.toString());
    }

    private void writeProductsTo(TagNode orderTag, Order order) {
        for (int j = 0; j < order.getProductCount(); j++) {
            Product product = order.getProduct(j);
            TagNode productTag=new TagNode("product");
            productTag.addAttribute("id",product.getId());
            productTag.addAttribute("color","red");
            writePriceTo(productTag,product);
            productTag.addValue(product.getName());
            orderTag.add(productTag);
//            xml.append("<product");
//            xml.append(" id='");
//            xml.append(product.getId());
//            xml.append("'");
//            xml.append(" color='");
//            xml.append("red");
//            xml.append("'");
//            xml.append(">");
//            writePriceTo(xml, product);
//            xml.append("name");
//            xml.append("<product>");
        }
    }

    private void writePriceTo(TagNode productTag, Product product) {
        TagNode priceNode = new TagNode("price");
        priceNode.addAttribute("currency", " USD ");
        priceNode.addValue("10");
        productTag.add(priceNode);

//        xml.append("<price");
//        xml.append(" currency='");
//        xml.append(" currencyValue");
//        xml.append("'>");
//        xml.append(" productPrice");
//        xml.append("</price>");
    }
}
